package com.wechat.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wechat.entity.WeChat;
import com.wechat.service.WeChatService;
import com.wechat.util.SignUtil;

import basic.base.web.BaseController;


@Controller
@RequestMapping(value = "/wechat/check")
public class WeChatController extends BaseController {
	private Logger logger = Logger.getLogger(WeChatController.class);

	@Autowired
	WeChatService service;

	/**
	 * 校验请求是否合法，仅接受微信请求
	 * 
	 * @param weChat
	 */
	@RequestMapping(method = { RequestMethod.GET }, produces = "application/json;charset=UTF-8")
	public void valid(WeChat weChat) {
		String signature = weChat.getSignature(); // 微信加密签名
		String timestamp = weChat.getTimestamp(); // 时间戳
		String nonce = weChat.getNonce();// 随机数
		String echostr = weChat.getEchostr();// 随机字符串
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		System.out.println("signature:"+signature);
		System.out.println("timestamp:"+timestamp);
		System.out.println("nonce:"+nonce);
		System.out.println("echostr:"+echostr);
		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			PrintWriter out;
			try {
				out = getResponse().getWriter();
				out.print(echostr);
				out.flush();
				out.close();
				System.out.println("=============echostr:"+echostr+"================");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			logger.error("不是微信服务器发来的请求,拒绝认证请求！");
		}

	}

	/**
	 * 消息的接收、处理、响应
	 * 
	 * @param request
	 * @param out
	 * @throws IOException
	 */
//	@RequestMapping(method = { RequestMethod.POST }, produces = "application/xml;charset=UTF-8")
//	public void dispose() throws IOException {
//		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
//		HttpServletRequest req = request;
//		req.setCharacterEncoding("UTF-8");
//		HttpServletResponse resp = response;
//		resp.setCharacterEncoding("UTF-8");
//		service.handleMsg(req, resp);
//	}

}
